<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'

import { Table } from '@/components/Table'
import {
  ucOrgAddApi,
  ucOrgBatchDelApi,
  ucOrgDelApi,
  ucOrgEditApi,
  ucOrgListApi,
  ucOrgSysRoleSetApi,
  ucOrgAdminExamineApi
} from '@/api/uc/org'

import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/uc/org/types'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Examine from './components/Examine.vue'
import SetSysRole from './components/SetSysRole.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter } from 'vue-router'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const { push } = useRouter()
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconDept = useIcon({ icon: 'mingcute:department-fill' })
const iconUser = useIcon({ icon: 'ep:user' })
const iconRole = useIcon({ icon: 'eos-icons:cluster-role' })
const iconSetSysRole = useIcon({ icon: 'eos-icons:role-binding-outlined' })
const iconExamine = useIcon({ icon: 'ep:checked' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  TableData
>({
  getListApi: ucOrgListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'org_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'org_name',
    label: '组织名称',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'org_type',
    label: '组织类型',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('org_type', cellValue)
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.org_type
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.org_type
      },
      show: true
    }
  },
  {
    field: 'state',
    label: '审核状态',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('org_state', cellValue)
    },
    form: {
      // component: 'Select',
      // componentProps: {
      //   options: dict.org_state
      // },
      show: false
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.org_state
      },
      show: true
    }
  },
  // {
  //   field: 'is_stop',
  //   label: '是否停用',
  //   width: 80,
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return h(
  //       ElTag,
  //       {
  //         type: cellValue == '0' ? 'success' : cellValue == '1' ? 'warning' : 'danger'
  //       },
  //       () => (cellValue == '0' ? '启用' : cellValue == '1' ? '停用' : '未知')
  //     )
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       options: [
  //         {
  //           label: '启用',
  //           value: '0'
  //         },
  //         {
  //           label: '停用',
  //           value: '1'
  //         }
  //       ]
  //     }
  //   }
  // },
  {
    field: 'business_license',
    label: '营业执照',
    table: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'business_license_img',
    label: '营业执照照片地址',
    table: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Upload'
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'identity_card',
    label: '身份证号',
    table: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'identity_card_front',
    label: '身份证正面照片',
    table: {
      show: false
    },
    form: {
      component: 'Upload',
      colProps: {
        span: 12
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'identity_card_back',
    label: '身份证反面照片',
    table: {
      show: false
    },
    form: {
      component: 'Upload',
      colProps: {
        span: 12
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'owner_user_name',
    label: '所有者',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'owner_sys_role_name',
    label: '所有者角色',
    width: 120,
    form: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'update_user_name',
    label: '修改人',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'update_time',
    label: '修改时间',
    width: 170,
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 325,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.org_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await ucOrgBatchDelApi({ ids: ids.join(',') })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}

const actionType = ref('')

const action = async (type: string, row: TableData = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.org_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'examine':
      dialogTitle.value = '审核'
      // tableObject.currentRow = { ...row, owner_sys_role_id: 2, owner_sys_role_name: '组织管理员' }
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'setSysRole':
      dialogTitle.value = '设置系统角色'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'dept':
      push({
        path: '/uc/org/org-dept',
        query: {
          org_id: row.org_id
        }
      })
      break
    case 'user':
      push({
        path: '/uc/org/org-user',
        query: {
          org_id: row.org_id
        }
      })
      break
    case 'role':
      push({
        path: '/uc/org/org-role',
        query: {
          org_id: row.org_id
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (org_id) => {
  let delRes = await ucOrgDelApi({ org_id: org_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const setSysRoleRef = ref<ComponentRef<typeof SetSysRole>>()
const examineRef = ref<ComponentRef<typeof Examine>>()
const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await ucOrgEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          data.state = '1'
          let res = await ucOrgAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'examine':
      const examineRole = unref(examineRef)
      await examineRole?.elFormRef()?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const examineData: any = (await examineRole?.getData()) as TableData
          // console.log('examineData', examineData)
          let newData: any = {
            terminal_type: examineData.terminal_type,
            org_id: tableObject.currentRow?.org_id,
            state: examineData.state
          }
          let res = await ucOrgAdminExamineApi(newData)
            .catch((resData) => {
              console.log(222, resData)
            })
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'setSysRole':
      const setSysRole = unref(setSysRoleRef)
      await setSysRole?.elFormRef()?.validate(async (isValid) => {
        // console.log(isValid)
        if (isValid) {
          loading.value = true
          const data: any = (await setSysRole?.getData()) as TableData
          let newData: any = {
            owner_user_id: data.owner_user_id,
            owner_sys_role_id: data.owner_sys_role_id,
            org_id: data.org_id
          }
          let res = await ucOrgSysRoleSetApi(newData)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state == 2"
          circle
          :icon="iconDept"
          @click="action('dept', row)"
          title="部门"
        />
        <ElButton
          v-if="row.state == 2"
          circle
          :icon="iconUser"
          @click="action('user', row)"
          title="人员"
        />
        <ElButton
          v-if="row.state == 2"
          circle
          :icon="iconRole"
          @click="action('role', row)"
          title="角色"
        />
        <ElButton
          v-if="row.state != 2"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconExamine"
          @click="action('examine', row)"
          title="审核"
        />
        <ElButton
          v-else
          circle
          :icon="iconSetSysRole"
          @click="action('setSysRole', row)"
          title="设置系统角色"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <Examine v-if="actionType == 'examine'" ref="examineRef" :data="tableObject.currentRow" />

    <SetSysRole
      v-if="actionType == 'setSysRole'"
      ref="setSysRoleRef"
      :data="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'see'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
